package cn.springcloud.fix.novel.biz.service.impl;

import cn.springcloud.fix.novel.biz.service.AsyncTestService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

@Slf4j
@Service
@AllArgsConstructor
public class AsyncTestServiceImpl implements AsyncTestService {

    private AsyncTest asyncTest;

    @Override
    public String noReturn(String name) {
        long start = System.currentTimeMillis();
        noReturnAsync(name);
        long end = System.currentTimeMillis();
        log.info("耗时：" + (int) (end - start));
        return "hello " + name;
    }

    @Override
    public String requestAnsync(String name) {
        try {
            Long start = System.currentTimeMillis();
            Future<String> result = asyncTest.ansync(name);
            if (result.isDone()) {
                name = result.get();
                log.info("异步方法结束，名字改为：" + name);
            }
            Long end = System.currentTimeMillis();
            log.info("耗时：" + (int) (end - start));
            return "hello " + name;
        } catch (Exception e) {
            log.error("异常");
            return "异常";
        }
    }

    @Override
    public String noGet(String name) {
        Long start = System.currentTimeMillis();
        asyncTest.ansync(name);
        Long end = System.currentTimeMillis();
        log.info("耗时：" + (int) (end - start));
        return "hello " + name;
    }

    @Async
    public void noReturnAsync(String name) {
        try {
            Thread.sleep(50000);
            log.info("这里是异步方法");
            log.info("传过来的名字是：" + name);
            name = "修改的名字";
            log.info("修改后的名字是：" + name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
